<?php

/**
 * C
 * 配置参数管理函数
 *
 * C('name')
 * C('a.name')
 *
 * @param mixed $k  可以单级key，也可以是多级key，多级key之间用圆点分割，多级key只适用于获取数据时
 *                  如果不指定$k，则表示获取所有配置参数
 * @param mixed $v
 * @access public
 * @return void
 */
function C($k = null, $v = null) {
    static $config = [];

    if (is_null($k)) {
        return $config;
    }

    if (is_array($k)) {
        $config = array_merge($config, $k);

        return $k;
    }

    if (is_null($v)) {
        return $config[$k] ?? null;
    }

    /**
     * 分解多级下标
     */
    if (strpos('.', $k) === false) {
        return $config[$k] = $v;
    }

    $keys = explode('.', $k);
    $d    = $config;

    foreach ($keys as $k => $v) {
        $d = $d[$k] ?? null;

        if (is_null($d)) {
            return $d;
        }
    }

    return $d;
}

/**
 * get_pdo_dsn
 * 返回解析后的dsn字符串
 *
 * 传入的$conf参数中必须包含函数体内$conf引用的下标
 *
 * @param mixed $conf
 * @access public
 * @return void
 */
function get_pdo_dsn($conf = null) {
    $conf = $conf ?? C();

    return str_replace(
        ['{type}',         '{host}',         '{port}',         '{dbname}',       '{user}',         '{password}'],
        [$conf['DB_TYPE'], $conf['DB_HOST'], $conf['DB_PORT'], $conf['DB_NAME'], $conf['DB_USER'], $conf['DB_PWD']],
        $conf['PDO_DSN']
    );
}


function get_db_connect() {
    $dsn = C('dsn');

    try {
        return new \PDO($dsn);
    } catch(\Exception $e) {
        throw new \Exception($e->getMessage());
    }
}

/**
 * collect
 *
 * @param mixed $url
 * @return void
 */
function collect($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   //不直接输出获取的数据
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);   //连接超时，3秒如果连接不成功，则超时
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 5000); //尝试重连超时时间，单位毫秒
    curl_setopt($ch, CURLOPT_TIMEOUT, 6); // 执行超时(秒)，一定要加上此项，否则有时可能因$url访问不成功导致进程阻塞
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:28.0) Gecko/20100101 Firefox/28.0');
    $r = curl_exec($ch);
    curl_close($ch);

    return $r;
}

/**
 * collect_base_stats
 * 获取综合统计信息，主要是带宽、负载、运行时间
 *
 * @param mixed $baseUrl
 * @return void
 */
function collect_base_stats($baseUrl) {
    $url = $baseUrl . '/stats/api/stats.php';

    if(!$tmp = collect($url)) {
        return false;
    }

    return ($r = json_decode($tmp, true)) ? $r : false;
}
